package main

import (
	"fmt"
	"log"

	"github.com/astaxie/beego/orm"

	_ "github.com/go-sql-driver/mysql"
)

type User struct {
	Id       int        `json:"id"`
	Name     string     `json:"name"`
	Articles []*Article `orm:"reverse(many)"`
}

type Article struct {
	Id       int          `json:"id"`
	Title    string       `json:"title"`
	Content  string       `json:"content"`
	User     *User        `json:"user" orm:"rel(fk)"`
	Type     *Articletype `json:"type" orm:"rel(fk)"`
	Comments []*Comment   `orm:"reverse(many)"` //反向一对多关联
}

type Articletype struct {
	Id       int        `json:"id"`
	Name     string     `json:"name"`
	Orderno  int        `json:"orderno"`
	Articles []*Article `orm:"reverse(many)"`
}

type Comment struct {
	Id    int      `json:"id"`
	Cname string   `json:"cname"`
	Aid   *Article `json:"article" orm:"rel(fk)"`
}

func init() {
	orm.RegisterDriver("mysql", orm.DRMySQL)

	// set default database
	orm.RegisterDataBase("default", "mysql", "root:@/orm_test?charset=utf8", 30)

	// register model
	orm.RegisterModel(new(User), new(Article), new(Articletype), new(Comment))

	err := orm.RunSyncdb("default", false, true)
	if err != nil {
		log.Fatalf(err.Error())
	}

	orm.Debug = true
}

func main() {
	var articles []*Article
	orm.NewOrm().QueryTable("article").Filter("User", 1).RelatedSel().All(&articles)
	for _, v := range articles {
		fmt.Println(v)
		fmt.Println(">> User Info: ", v.User)
		fmt.Println(">> ", v.Type)
	}

	var user User
	err := orm.NewOrm().QueryTable("user").Filter("Name", "kevin").Limit(1).One(&user)
	if err == nil {
		fmt.Println(user)
	}

	var comment []*Comment
	orm.NewOrm().QueryTable("comment").Filter("Aid", 3).RelatedSel().All(&comment)
	for _, v := range comment {
		fmt.Println(v)
		fmt.Println(">> Article: ", v.Aid)
		fmt.Println(">>> ", v.Aid.User, v.Aid.Content)
	}
}
